package com.atomscat.lottery.service;

import com.atomscat.lottery.entity.db.LotteryUserEntity;
import com.atomscat.lottery.entity.vo.request.PageLotteryUserRequest;
import com.atomscat.lottery.repository.LotteryRecordRepository;
import com.atomscat.lottery.repository.LotteryUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class LotteryUserService {
    private final LotteryUserRepository lotteryUserRepository;

    public Page<LotteryUserEntity> pageLotteryUserEntity(PageLotteryUserRequest pageLotteryUserRequest) {
        PageRequest pageable = PageRequest.of(pageLotteryUserRequest.getPageNumber(), pageLotteryUserRequest.getPageSize());
        LotteryUserEntity lotteryUserEntity = new LotteryUserEntity();
        return lotteryUserRepository.findAll(Example.of(lotteryUserEntity), pageable);
    }

    public Page<LotteryUserEntity> pageDrawLotteryUser(PageLotteryUserRequest pageLotteryUserRequest) {
        PageRequest pageable = PageRequest.of(pageLotteryUserRequest.getPageNumber(), pageLotteryUserRequest.getPageSize());
        return lotteryUserRepository.findByActivityId(pageLotteryUserRequest.getActivityId(), pageable);
    }

    @Transactional
    public void saveLotteryUser(LotteryUserEntity lotteryUserEntity) {
        LotteryUserEntity lotteryUser = new LotteryUserEntity();
        lotteryUser.setAppid(lotteryUserEntity.getAppid());
        lotteryUser.setOpenid(lotteryUserEntity.getOpenid());
        lotteryUserRepository.findOne(Example.of(lotteryUser)).stream().forEach(db -> {
            lotteryUserEntity.setId(db.getId());
        });
        lotteryUserRepository.saveAndFlush(lotteryUserEntity);
    }

    public LotteryUserEntity updateLotteryUser(LotteryUserEntity lotteryUserEntity) {
        return  lotteryUserRepository.saveAndFlush(lotteryUserEntity);
    }

}
